package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.BuyerBean;
import com.project.bean.BuyerCarBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyerCarMapper;
import com.project.mapper.IBuyerInfoMapper;
import com.project.mapper.IBuyerMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyerCarService;
import com.project.service.IBuyerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class BuyerServiceImpl implements IBuyerService {
    @Autowired
    private IBuyerMapper buyerMapper;

    @Autowired
    IBuyerInfoMapper buyerInfoMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IBuyerCarMapper buyerCarMapper;

    @Override
    public IPage<BuyerBean> findByItem(Integer pageNO, String name, LocalDate startDate, LocalDate endDate) {
        return buyerMapper.findByItem(new Page(pageNO,3),name,startDate,endDate);
    }

    @Override
    public BuyerBean findById(Integer buyerId) {
        BuyerBean buyerBean = buyerMapper.findById(buyerId);
        buyerBean.setBuyerInfo(buyerInfoMapper.findList(buyerId));
        return buyerBean;

    }

    @Override
    public void addBuyer(BuyerBean buyer, Integer userId) {
        buyerMapper.insert(buyer);
        List<BuyerCarBean> List = buyerCarMapper.findByUserId(userId);
        buyerInfoMapper.addBuyerInfo(List, buyer.getId());
        for (BuyerCarBean carBean : List
        ) {
            ProductBean productBean = productMapper.selectById(carBean.getProductId());
            productBean.setBuyPrice(carBean.getBuyMoney());
            productBean.setNum(productBean.getNum() + carBean.getNum());
            productMapper.updateById(productBean);
        }
        QueryWrapper<BuyerCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        buyerCarMapper.delete(qw);
    }
}
